package com.zh.zhong.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.GlobalEventExecutor;
import java.util.concurrent.ConcurrentHashMap;

/**
 * MyChannelHandlerPool
 * 通道组池，管理所有websocket连接
 */
public class ChannelHandler {

    public ChannelHandler(){}

    //String=username
    public static final ConcurrentHashMap<String, Channel> channelIdMap = new ConcurrentHashMap<>();
    //只做群发的群组
    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    public static void add(String username,Channel channel){
        channelIdMap.put(username,channel);
    }

    public static void add(Channel channel){
        channelGroup.add(channel);
    }


    public static void remove(Channel channel){
        channelIdMap.remove(channel);
        AttributeKey<String> attr = AttributeKey.valueOf("username");
        channelIdMap.remove(channel.attr(attr));
    }

    public static Channel findByUsername(String username){
        return channelIdMap.get(username);
    }

    public static Channel findByChannelId(ChannelId channelId){
        return channelGroup.find(channelId);
    }

}